package src.unapec.seguridad.ejemplos.EncriptacionString;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import src.unapec.seguridad.ejemplos.Utils.Key;

public class Encriptacion {

	Cipher ecipher;
	Cipher dcipher;

	public String encrypt(String str, SecretKey key) {

		byte[] enc = null;

		try {
			// Encode the string into bytes using utf-8
			ecipher = Cipher.getInstance("DES");
			ecipher.init(Cipher.ENCRYPT_MODE, key);

			byte[] utf8 = str.getBytes("UTF8");

			enc = ecipher.doFinal(utf8);

		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {

			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
	
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {

			e.printStackTrace();
		} catch (BadPaddingException e) {

			e.printStackTrace();
		}            
		// Encode bytes to base64 to get a string
		return new sun.misc.BASE64Encoder().encode(enc);

	}


	public String decrypt(String str, SecretKey key) {


			// Decrypt
			byte[] utf8 = null;
			
			try {
				// Decode base64 to get bytes
				dcipher = Cipher.getInstance("DES");
				dcipher.init(Cipher.DECRYPT_MODE, key);
				byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

				utf8 = dcipher.doFinal(dec);
				
				return new String(utf8, "UTF8");
				
			} catch (InvalidKeyException e) {

				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {

				e.printStackTrace();
			} catch (NoSuchPaddingException e) {

				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {

				e.printStackTrace();
			} catch (BadPaddingException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			
			return null;
			
		
		
	}


	//Here's an example that uses the class:

	public static void main(String[] args) {

		try {
			
			Encriptacion encrypter = new Encriptacion();	    

			// Encrypt
			System.out.println(encrypter.encrypt("Java Rulezzzzzzz!!! !@#$%^&*() ",new Key().getKeys(1)));


			// Decrypt
			//System.out.println(encrypter.decrypt("CC7urfzROTPxQ6wIUvjvcuf7TOK1jRYlfZkq5H4NjN8=",new Key().getKeys(1)));


		} catch (Exception e) {
		}

	}
}